import { login } from "@/api/common";
import { localStorage } from "@/utils/storage";

export const getCode = () => {
  return new Promise((resolve, reject) => {
    uni.getProvider({
      service: "oauth",
      success: (res: any) => {
        uni.login({
          provider: res.provider[0],
          success: async (loginRes: any) => {
            resolve(loginRes.code);
          },
        });
      },
      fail(result) {
        reject(result);
      },
    });
  });
};

export const getToken = async () => {
  return new Promise(async (resolve, reject) => {
    const code = await getCode();
    const uid = localStorage.get("uid");

    login({
      code: code || "",
      uid: uid || "",
    })
      .then((res: any) => {
        if (res.code == 200) {
          const openid = res.data.openid;
          const token = res.data.token;

          localStorage.set("openid", openid);
          localStorage.set("token", token);

          resolve(token);
        } else if (res.code == 99998) {
          uni.showToast({
            title: "需要找管理员开通账号",
          });
        } else if (res.code == 99999) {
          uni.showToast({
            title: "您已被禁止访问",
          });
        } else {
          uni.showToast({
            title: res.message,
          });
        }
      })
      .catch((err) => reject(err));
  });
};
